package zerox

import (
	"net/http"

	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
)

//定义请求方式不对时返回
func allowedHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		httpx.OkJson(w, Body{Code: 405, Msg: "Method not allowed"})
	})
}

//定义不存在时返回
func foundHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		httpx.OkJson(w, Body{Code: 404, Msg: "not found"})
	})
}

//定义没有权限
func authorizedCallback() func(http.ResponseWriter, *http.Request, error) {
	return func(w http.ResponseWriter, r *http.Request, err error) {
		httpx.OkJson(w, Body{Code: 401, Msg: "Unauthorized"})
	}
}

//获取所有定义的run option
func GetOptions() []rest.RunOption {
	return []rest.RunOption{
		rest.WithNotAllowedHandler(allowedHandler()),
		rest.WithNotFoundHandler(foundHandler()),
		rest.WithUnauthorizedCallback(authorizedCallback()),
	}

}

//定义出错时返回
func SetErrorHandler() {
	httpx.SetErrorHandler(func(err error) (int, interface{}) {
		return 200, &Body{
			Code: 400,
			Msg:  err.Error(),
		}

	})
}
